<template>
  <Modal v-model="status"
         title="手动录入巡河记录"
         width="800"
         :mask-closable="false"
         @on-cancel="hide">
    <Form :model="model"
          ref="JPatrolForm"
          :label-width='120'
          label-position="left"
          :rules="rules">
      <Row type="flex"
           justify="space-between">
        <Col span="11">
        <Form-item label="河长"
                   prop="username">
          <Select v-model="model.username"
                  filterable
                  placeholder="请选择河长"
                  @on-change="chooseUser">
            <Option v-for="user in userList"
                    :value="user.username"
                    :key="'username_' + user.username">{{ user.realname }}</Option>
          </Select>
        </Form-item>
        </Col>
        <Col span="11">
        <Form-item label="请选择河长助理"
                   prop="ass_username">
          <Select v-model="model.ass_username"
                  clearable
                  filterable
                  placeholder="请选择河长助理">
            <Option v-for="assistant in assistantList"
                    :value="assistant.username"
                    :key="'ass_username_' + assistant.username">{{assistant.realname }}</Option>
          </Select>
        </Form-item>
        </Col>
      </Row>
      <Form-item label="巡查河流"
                 prop="river_no"
                 style="margin-bottom:30px">
        <Select @on-change="drawPath"
                v-model="model.river_no"
                ref="riverSelect"
                transfer
                clearable
                filterable
                placeholder="请选择巡查河流">

          <Option v-for="(river, ridx) in riverList"
                  :value="river.river_no"
                  :key="'river_no_' + ridx + river.river_no">{{ river.area}}-{{river.town}}-{{river.river_name }}</Option>
        </Select>
      </Form-item>

      <Form-item label="巡查天气"
                 prop="weather"
                 style="margin-bottom:30px">
        <Input v-model="model.weather"
               :maxlength="30"
               placeholder="请输入巡查天气" />
      </Form-item>

      <Form-item label="河段具体位置"
                 prop="location"
                 style="margin-bottom:30px">
        <Input v-model="model.location"
               :maxlength="30"
               placeholder="请输入河段位置" />
      </Form-item>

      <Form-item label="巡查方式"
                 prop="patrol_way"
                 style="margin-bottom:30px">
        <Select v-model="model.patrol_way"
                transfer
                filterable
                placeholder="请选择巡查方式"
                @on-change="changePatrolWay">
          <Option value="步行">步行</Option>
          <Option value="乘船">乘船</Option>
          <Option value="无人机">无人机</Option>
        </Select>
      </Form-item>

      <Row type="flex"
           justify="space-between">
        <Col span="11">
        <Form-item label="开始时间"
                   prop="start_time">
          <DatePicker format="yyyy-MM-dd HH:mm:ss"
                      type="datetime"
                      :value="model.start_time"
                      :options="optionsDate"
                      placeholder="请选择事件开始时间"
                      @on-change="changeStartTime" />
        </Form-item>
        </Col>
        <Col span="11">
        <Form-item label="结束时间"
                   prop="end_time">
          <DatePicker format="yyyy-MM-dd HH:mm:ss"
                      type="datetime"
                      :value="model.end_time"
                      :options="optionsDate"
                      placeholder="请选择事件结束时间"
                      @on-change="changeEndTime" />
        </Form-item>
        </Col>
      </Row>

      <Form-item label="上传景观图片"
                 prop="scenerys">
        <div class="demo-upload-list"
             v-for="(item,index) in sceneryList"
             :key="'scenerys_' + index">
          <template>
            <img :src="item" />
            <div class="demo-upload-list-cover">
              <Icon type="ios-trash-outline"
                    @click.native="removeScenery(index)" />
            </div>
          </template>

        </div>
        <Upload ref="JScenery"
                :show-upload-list="false"
                :on-success="uploadScenery"
                :format="['jpg','jpeg','png']"
                :max-size="20480"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                multiple
                type="drag"
                :action="uploadUrl"
                style="display: inline-block;width:58px;">
          <div style="width: 58px;height:58px;line-height: 58px;">
            <Icon type="ios-camera"
                  size="20" />
          </div>
        </Upload>
      </Form-item>

      <Form-item class="upload_file"
                 label="工作简报">
        <template v-if="!model.prove_file.path">
          <Upload ref="JFile"
                  :format="['jpg', 'jpeg', 'png', 'doc', 'docx', 'pdf']"
                  :on-format-error="filehandleFormatError"
                  :show-upload-list="false"
                  type="drag"
                  :on-success="filehandleSuccess"
                  :max-size="20480"
                  :on-exceeded-size="handleMaxSize"
                  :action="fileUrl">
            <div>
              <Icon type="ios-cloud-upload"
                    size="23"
                    style="color: #52A1FD;height: 100%;vertical-align: middle;" />
              <span>上传工作简报</span>
            </div>
          </Upload>
          <span class="tips">单个文件不能超过20M</span>
        </template>
        <template v-else>
          <a target="_blank"
             :href="model.prove_file.path">{{model.prove_file.filename}}</a>
          <Icon size="18"
                style="margin-left: 5px;color: #999;cursor: pointer;width:18px;height:18px;line-height:18px"
                @click.native="removeFile"
                type="ios-close-circle" />
        </template>
      </Form-item>

      <Form-item label="巡河路线"
                 prop="route"
                 style="margin-bottom:30px">
        <i-col span="24">
          <Button type="primary"
                  @click="repaintMap"
                  v-if="isRepaint"
                  class="repaint-btn">重绘</Button>
        <div id="patrol-map"
             style="width:100%;height: 200px;"></div>
        </i-col>
      </Form-item>

      <div class="sub-title">巡河记录表</div>

      <!-- 是否发现问题 -->
      <FormItem label="是否发现问题"
                required>
        <RadioGroup v-model="isNormal"
                    @on-change="changeIsNormal">
          <Radio label="一切正常" />
          <Radio label="存在问题" />
        </RadioGroup>
      </FormItem>

      <FormItem label="处理方式"
                required
                v-if="isNormal==='存在问题'">
        <RadioGroup v-model="model.solve_way"
                    @on-change="chooseHandleWay">
          <Radio label="自行处理" />
          <Radio label="上报处理" />
        </RadioGroup>
      </FormItem>

      <Form-item v-if="isNormal==='存在问题'"
                 label="事件地点"
                 prop="lat"
                 style="margin-bottom:30px">
        <Input v-show="false"
               v-model="model.lat" />
        <div id="event-map"
             style="height: 200px;" />
      </Form-item>

      <FormItem v-if="isNormal==='存在问题'"
                label="问题类型"
                prop="problem_types">
        <CheckboxGroup v-model="model.problem_types">
          <Checkbox label="杂物漂浮" />
          <Checkbox label='污水直排' />
          <Checkbox label='水体异样' />
          <Checkbox label='护岸损毁' />
          <Checkbox label='非法采砂' />
          <Checkbox label='侵占河道' />
          <Checkbox label='非法捕鱼' />
          <Checkbox label='四乱问题' />
          <Checkbox label='五清问题' />
          <Checkbox label='其他' />
        </CheckboxGroup>
      </FormItem>

      <FormItem v-if="isNormal==='存在问题'"
                label="问题描述"
                prop="overview">
        <Input v-model="model.overview"
               :maxlength="200"
               show-word-limit
               type="textarea"
               placeholder="请输入问题描述" />
      </FormItem>

      <Form-item v-if="isNormal==='存在问题'"
                 label="相关照片"
                 prop="photos"
                 style="margin-bottom:0">
        <div class="demo-upload-list"
             v-for="(item,index) in photoList"
             :key="'photos_' + index">
          <img :src="item" />
          <div class="demo-upload-list-cover">
            <Icon type="ios-trash-outline"
                  @click.native="removePhoto(index)" />
          </div>
        </div>
        <Upload ref="JPhoto"
                :show-upload-list="false"
                :on-success="uploadPhoto"
                :format="['jpg','jpeg','png']"
                :max-size="20480"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                multiple
                type="drag"
                :action="uploadUrl"
                style="display: inline-block;width:58px;">
          <div style="width: 58px;height:58px;line-height: 58px;">
            <Icon type="ios-camera"
                  size="20" />
          </div>
        </Upload>
      </Form-item>

      <Form-item v-if="isNormal==='存在问题' && model.solve_way==='自行处理'"
                 label="处理结果"
                 prop="solve_result">
        <Input v-model="model.solve_result"
               :maxlength="200"
               show-word-limit
               type="textarea"
               placeholder="请输入处理结果" />
      </Form-item>

      <Form-item v-if="isNormal==='存在问题' && model.solve_way==='自行处理'"
                 label="处理照片"
                 prop="solve_file"
                 style="margin-bottom:0">
        <div class="demo-upload-list"
             v-for="(item,index) in solveList"
             :key="'solve_file_' + index">
          <img :src="item" />
          <div class="demo-upload-list-cover">
            <Icon type="ios-trash-outline"
                  @click.native="removeSolve(index)" />
          </div>
        </div>
        <Upload ref="JSolve"
                :show-upload-list="false"
                :on-success="uploadSolve"
                :format="['jpg','jpeg','png']"
                :max-size="20480"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                multiple
                type="drag"
                :action="uploadUrl"
                style="display: inline-block;width:58px;">
          <div style="width: 58px;height:58px;line-height: 58px;">
            <Icon type="ios-camera"
                  size="20" />
          </div>
        </Upload>
      </Form-item>
    </Form>
    <div slot="footer">
      <Button type="primary"
              @click="submit">保存</Button>
      <Button @click="hide">取消</Button>
    </div>
  </Modal>
</template>

<script>
import { ajaxPost } from 'global/axios';
import storage from 'good-storage';
import { domain, domain2 } from 'global/setting';

export default {
  data() {
    return {
      status: false,
      isRepaint: false, // 是否重绘
      isDrawPath: false, // 是否有河流轨迹

      uploadUrl: `${domain}/filemanage/uploadphoto?dir=data/patrol/app/${new Date().format(
        'yyyy-MM-dd'
      )}&token=${storage.session.get('token')}`,

      fileUrl: `${domain}/emergency/patrol/upload?dir=provefile&token=${storage.session.get(
        'token'
      )}`,

      isNormal: '一切正常',

      model: {
        username: '',
        river_no: '',
        river_name: '',
        start_time: '',
        end_time: '',
        weather: '',
        location: '',
        overview: '',
        ass_username: '',
        patrol_way: '步行',
        lat: '',
        lng: '',
        address: '',
        problem_types: [],
        scenerys: [],
        prove_file: {
          filename: '',
          path: '',
        },
        solve_way: '上报处理',
        route: [],
        solve_file: [],
        photos: [],
        solve_result: '',
      },

      optionsDate: {
        disabledDate(date) {
          let today = new Date();
          return (
            date &&
            date.valueOf() >
              new Date(
                `${today.getFullYear()}-${
                  today.getMonth() + 1
                }-${today.getDate()} 23:59:59`
              ).getTime()
          );
        },
      },

      rules: {
        username: [
          { required: true, message: '河长不能为空', trigger: 'change' },
        ],
        river_no: [
          { required: true, message: '河流不能为空', trigger: 'change' },
        ],
        weather: [{ required: true, message: '天气不能为空', trigger: 'blur' }],
        location: [
          { required: true, message: '位置不能为空', trigger: 'blur' },
        ],
        start_time: [
          { required: true, message: '开始时间不能为空', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              let currentTime = Date.now();
              let startTime = new Date(value).getTime();
              if (startTime > currentTime) {
                callback(new Error('开始时间不能超出当前时间'));
                return;
              }
              if (this.model.end_time) {
                let endTime = new Date(this.model.end_time).getTime();
                if (startTime >= endTime) {
                  callback(new Error('开始时间不能在结束时间之后'));
                  return;
                }
                if (
                  this.model.patrol_way === '步行' &&
                  endTime - startTime < 600000
                ) {
                  callback(new Error('巡河时间必须大于10分钟'));
                  return;
                }
              }
              callback();
            },
            trigger: 'change',
          },
        ],
        end_time: [
          { required: true, message: '结束时间不能为空', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              let currentTime = Date.now();
              let endTime = new Date(value).getTime();
              if (endTime > currentTime) {
                callback(new Error('结束时间不能超出当前时间'));
                return;
              }
              if (this.model.start_time) {
                let startTime = new Date(this.model.start_time).getTime();
                if (startTime >= endTime) {
                  callback(new Error('结束时间不能在开始时间之前'));
                  return;
                }
                if (
                  this.model.patrol_way === '步行' &&
                  endTime - startTime < 600000
                ) {
                  callback(new Error('巡河时间必须大于10分钟'));
                  return;
                }
              }
              callback();
            },
            trigger: 'change',
          },
        ],
        scenerys: [
          {
            required: true,
            message: '请上传2~3张景观图片',
            type: 'array',
            min: 2,
            max: 3,
            trigger: 'change',
          },
        ],
        route: [
          {
            required: true,
            message: '请描画路线',
            type: 'array',
            min: 2,
            trigger: 'change',
          },
        ],
        problem_types: [
          {
            required: true,
            message: '请选择问题',
            type: 'array',
            min: 1,
            trigger: 'change',
          },
        ],
        overview: [
          { required: true, message: '请输入问题描述', trigger: 'blur' },
        ],

        photos: [
          {
            required: true,
            message: '请上传相关照片',
            type: 'array',
            min: 1,
            trigger: 'change',
          },
        ],
        solve_file: [
          {
            required: true,
            message: '请上传处理照片',
            type: 'array',
            min: 1,
            trigger: 'change',
          },
        ],
        solve_result: [
          {
            required: true,
            message: '请输入处理结果',
            trigger: 'blur',
          },
        ],
        patrol_way: [{ required: true, message: '', trigger: 'change' }],
        lat: [
          {
            required: true,
            message: '请选择事件地点',
            trigger: 'change',
            type: 'number',
          },
        ],
      },

      riverLocation: {
        lat: '',
        lng: '',
      },

      saveCenter: {}, // 地图位置

      userList: [],
      riverList: [],
      sceneryList: [],
      solveList: [],
      assistantList: [],
      photoList: [],
      lakePath: [],
    };
  },

  mounted() {
    this.getUser();
    this.getRiver();
  },

  methods: {
    show() {
      this.status = true;
      this.$nextTick(() => {
        this.showMap();
      });
    },

    hide() {
      this.$refs.JPatrolForm.resetFields();
      this.isNormal = '一切正常';
      this.model = {
        username: '',
        river_no: '',
        areatown: '',
        river_name: '',
        start_time: '',
        end_time: '',
        weather: '',
        ass_username: '',
        patrol_way: '步行',
        location: '',
        overview: '',
        address: '',
        lat: '',
        problem_types: [],
        scenerys: [],
        prove_file: {
          filename: '',
          path: '',
        },
        solve_way: '上报处理',
        route: [],
        solve_file: [],
        photos: [],
        solve_result: '',
      };
      this.lakePath = [];
      this.sceneryList = [];
      this.solveList = [];
      this.photoList = [];
      this.$refs.JSolve && this.$refs.JSolve.clearFiles();
      this.$refs.JScenery && this.$refs.JScenery.clearFiles();
      this.$refs.JFile && this.$refs.JFile.clearFiles();
      this.$refs.JPhoto && this.$refs.JPhoto.clearFiles();

      this.status = false;
    },

    submit() {
      this.$refs.JPatrolForm.validate(valid => {
        if (!valid) {
          return false;
        }
        let {
          river_no,
          river_name,
          areatown,
          start_time,
          end_time,
          username,
          weather,
          prove_file,
          scenerys,
          route,
          location,
          patrol_way,
          ass_username,
        } = this.model;

        let data = {
          username,
          river_no,
          river_name,
          start_time,
          scenerys,
          end_time,
          route,
          ass_username,
          patrol_report: { weather, location, areatown },
        };

        if (
          storage.session.get('type') === '4' &&
          storage.session.get('level') === 2
        ) {
          if (prove_file.path === '') {
            this.$Message.warning({
              content: '请上传工作简报',
            });
            return false;
          }
        }

        prove_file.path && (data.prove_file = prove_file);
        patrol_way !== '步行' && (data.patrol_way = patrol_way);

        if (this.isNormal === '存在问题') {
          let {
            problem_types,
            solve_way,
            solve_file,
            lat,
            lng,
            overview,
            address,
            photos,
            solve_result,
          } = this.model;
          data.manual_report = {
            problem_types,
            lat,
            lng,
            overview,
            photos,
            address,
          };

          if (solve_way === '自行处理') {
            data.manual_report.solve_way = solve_way;
            data.manual_report.solve_file = solve_file;
            data.manual_report.solve_result = solve_result;
          }
        }

        ajaxPost({
          data,
          url: '/emergency/patrol/manualnew',
          token: storage.session.get('token'),
          success: res => {
            if (res.data.code === '0000') {
              this.$Loading.finish();
              this.$Message.success({
                content: '录入成功',
              });
              this.$emit('update');
              this.hide();
            } else {
              this.$Message.warning({
                content: res.data.message,
              });
            }
          },
        });
      });
    },

    changePatrolWay() {
      if (this.model.start_time) {
        this.$refs.JPatrolForm.validateField('start_time');
      }

      if (this.model.end_time) {
        this.$refs.JPatrolForm.validateField('end_time');
      }
    },

    chooseUser(data) {
      if (data) {
        let target = this.userList.find(item => item.username === data);
        this.getAssistant(target.userid);
      }
    },

    changeIsNormal() {
      if (this.isNormal === '一切正常') {
        this.model.overview = '';
        this.model.problem_types = [];
        this.model.solve_way = '上报处理';
        this.model.solve_result = '';
        this.model.photos = [];
        this.photoList = [];
        this.$refs.JPhoto && this.$refs.JPhoto.clearFiles();
      } else {
        this.$nextTick(() => {
          if (this.riverLocation.lat) {
            let { lat, lng } = this.riverLocation;
            this.showEventMap(lat, lng);
          } else {
            this.showEventMap();
          }
        });
      }
    },

    chooseHandleWay() {
      if (this.model.solve_way === '上报处理') {
        this.$refs.JSolve.clearFiles();
        this.model.solve_file = [];
        this.model.solve_result = '';
        this.solveList = [];
        this.model.overview = '';
      }
    },

    changeStartTime(val) {
      this.model.start_time = val;
    },

    changeEndTime(val) {
      this.model.end_time = val;
    },

    uploadPhoto({ result }) {
      let { path } = result;
      this.model.photos.push(path);
      this.photoList.push(`${domain2}${path}`);
    },

    uploadScenery({ result }) {
      let { path } = result;
      this.model.scenerys.push(path);
      this.sceneryList.push(`${domain2}${path}`);
    },

    removePhoto(index) {
      this.$refs.JPhoto.fileList.splice(index, 1);
      this.model.photos.splice(index, 1);
      this.photoList.splice(index, 1);
    },

    handleFormatError(file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: `文件格式不正确，请上传 jpg 或 png 格式的图片。`,
      });
    },

    handleMaxSize(file) {
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc: `文件太大，不能超过 20M。`,
      });
    },

    uploadSolve({ result }) {
      let { path } = result;
      this.model.solve_file.push(path);
      this.solveList.push(`${domain2}${path}`);
    },

    removeSolve(index) {
      this.$refs.JSolve.fileList.splice(index, 1);
      this.model.solve_file.splice(index, 1);
      this.solveList.splice(index, 1);
    },

    removeScenery(index) {
      this.$refs.JScenery.fileList.splice(index, 1);
      this.model.scenerys.splice(index, 1);
      this.sceneryList.splice(index, 1);
    },

    filehandleFormatError(file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: `文件格式不正确，请上传 word文档或者图片或者pdf。`,
      });
    },

    filehandleSuccess({ result }) {
      this.model.prove_file.path = result.path;
      this.model.prove_file.filename = result.filename;
    },

    removeFile() {
      this.model.prove_file = {
        path: '',
        filename: '',
      };
      this.$refs.JFile.clearFiles();
    },

    getUser() {
      ajaxPost({
        data: {
          searchValue: {
            user_type: '0,1,2,3|#|in',
          },
          fieldName: ['username', 'realname', 'userid'],
        },
        url: '/sys/userinfo/list',
        token: storage.session.get('token'),
        success: res => {
          this.$Loading.finish();
          this.userList = res.data.result.result;
        },
      });
    },

    getAssistant(chief_userid) {
      this.model.ass_username = '';
      ajaxPost({
        data: {
          chief_userid,
        },
        url: '/sys/userinfo/getmyass',
        token: storage.session.get('token'),
        success: res => {
          if (res.data.code === '0000') {
            this.assistantList = res.data.result;
          }
        },
      });
    },

    getRiver() {
      ajaxPost({
        data: {
          fieldName: ['river_name', 'river_no', 'area', 'town'],
          searchValue: {},
        },
        url: '/bsi/riverchief/list',
        token: storage.session.get('token'),
        success: res => {
          this.$Loading.finish();
          this.riverList = res.data.result.result;
        },
      });
    },

    showMap() {
      let myMap = document.getElementById('patrol-map');
      myMap.innerHTML = '';
      let center = new qq.maps.LatLng(23.02, 113.12);
      this.saveCenter = center; // 保存地图位置
      let maps = new qq.maps.Map(document.getElementById('patrol-map'), {
        center,
        zoom: 12,
        disableDoubleClickZoom: false,
      });
      let path = [];
      let listener = qq.maps.event.addListener(maps, 'click', event => {
        this.isRepaint = true; // 显示重绘按钮
        let cirle = new qq.maps.Circle({
          center: new qq.maps.LatLng(
            event.latLng.getLat(),
            event.latLng.getLng()
          ),
          radius: 4,
          fillColor: '#ff0000',
          map: maps,
        });
        path.unshift(
          new qq.maps.LatLng(event.latLng.getLat(), event.latLng.getLng())
        );
        let polyline = new qq.maps.Polyline({
          path,
          strokeColor: '#ff0000',
          strokeWeight: 3,
          editable: false,
          map: maps,
        });
        this.model.route.push({
          lat: event.latLng.getLat(),
          lng: event.latLng.getLng(),
        });
      });
    },

    showEventMap(lat = 23.02, lng = 113.12) {
      let center = new qq.maps.LatLng(lat, lng);
      let map = new qq.maps.Map(document.getElementById('event-map'), {
        center,
        zoom: 12,
        disableDoubleClickZoom: false,
      });

      qq.maps.event.addListener(map, 'click', event => {
        let { latLng } = event;
        let { lat, lng } = latLng;
        this.getStreet(lat, lng);
        let marker = new qq.maps.Marker({
          position: latLng,
          map,
        });

        qq.maps.event.addListener(map, 'click', () => marker.setMap(null));
        this.model.lat = lat;
        this.model.lng = lng;
      });

      if (this.lakePath.length > 0) {
        this.lakePath.forEach(path => {
          new qq.maps.Polyline({
            path,
            strokeColor: '#2d8cf0',
            strokeWeight: 2,
            editable: false,
            map,
          });
        });
      }
    },

    getStreet(lat, lng) {
      let data = {
        location: `${lat},${lng}`,
        key: 'AZ3BZ-RXPLW-DNZRV-RLXEG-NPASJ-EDB5Z',
        get_poi: 0,
      };
      data.output = 'jsonp';
      $.ajax({
        url: 'https://apis.map.qq.com/ws/geocoder/v1/?',
        type: 'get',
        dataType: 'JSONP',
        jsonp: 'callback',
        jsonpCallback: 'QQmap',
        data,
        success: ({
          result: {
            formatted_addresses: { recommend },
          },
        }) => {
          this.model.address = recommend;
        },
      });
    },

    drawPath(e) {
      if (!e) {
        return;
      }
      this.isDrawPath = true;
      this.isRepaint = false;
      this.model.route = [];
      let riverTarget = this.riverList.find(item => item.river_no === e);
      let { river_name, area, town } = riverTarget;
      this.model.river_name = river_name;
      this.model.areatown = `${area}-${town}`;

      ajaxPost({
        data: {
          river_no: e,
        },
        url: '/bsi/riverchief/find',
        token: storage.session.get('token'),
        success: res => {
          this.$Loading.finish();

          let row = res.data.result.river_geo;
          let lat = 23.02
          let lng = 113.12
          if(row[0] && row[0].route_gcj02) {
            lat = row[0].route_gcj02[0].lat
            lng = row[0].route_gcj02[0].lng
          }
          let maps = document.getElementById('patrol-map');
          maps.innerHTML = '';

          this.riverLocation = {
            lat: lat,
            lng: lng,
          };
          this.model.lat = '';
          this.model.lng = '';
          let center = new qq.maps.LatLng(
            lat,
            lng
          );
          this.saveCenter = center; // 保存地图位置
          let map = new qq.maps.Map(maps, {
            center,
            zoom: 12,
            disableDoubleClickZoom: true,
          });
          //手动绘制监听
          let path = [];
          let listener = qq.maps.event.addListener(map, 'click', event => {
            this.isRepaint = true; // 显示重绘按钮
            let cirle = new qq.maps.Circle({
              center: new qq.maps.LatLng(
                event.latLng.getLat(),
                event.latLng.getLng()
              ),
              radius: 4,
              fillColor: '#ff0000',
              map,
            });
            path.unshift(
              new qq.maps.LatLng(event.latLng.getLat(), event.latLng.getLng())
            );

            let polyline = new qq.maps.Polyline({
              path,
              strokeColor: '#ff0000',
              strokeWeight: 3,
              editable: false,
              map,
            });
            this.model.route.push({
              lat: event.latLng.getLat(),
              lng: event.latLng.getLng(),
            });
          });
          let lakePath = [];
          row.map(item => {
            let path = [];
            for (let i = 0; i < item.route_gcj02.length; i++) {
              path.push(
                new qq.maps.LatLng(
                  item.route_gcj02[i].lat,
                  item.route_gcj02[i].lng
                )
              );
            }
            lakePath.push(path);
            let polyline = new qq.maps.Polyline({
              path,
              strokeColor: '#2d8cf0',
              strokeWeight: 2,
              editable: false,
              map,
            });
          });
          this.lakePath = lakePath;

          if (this.isNormal === '存在问题') {
            this.showEventMap(
              lat,
              lng
            );
          }
        },
      });
    },

    repaintMap() { // 重绘
      let path = []; // 巡河路线轨迹
      let center = this.saveCenter; // 地图位置
      let map = new qq.maps.Map(document.getElementById('patrol-map'), {
        center,
        zoom: 12,
        disableDoubleClickZoom: false,
      });
      this.model.route = []; // 清除路径
      if(this.isDrawPath){ // 如果有河流轨迹
        // 如果有河流轨迹
        if (this.lakePath.length > 0) {
          this.lakePath.forEach(path => {
            new qq.maps.Polyline({
              path,
              strokeColor: '#2d8cf0',
              strokeWeight: 2,
              editable: false,
              map,
            });
          });
        }
      }

      // 绘制巡河路线
      let listener = qq.maps.event.addListener(map, 'click', event => {
        let circle = new qq.maps.Circle({
          center: new qq.maps.LatLng(
            event.latLng.getLat(),
            event.latLng.getLng()
          ),
          radius: 4,
          fillColor: '#ff0000',
          map: map,
        });
        path.unshift(
          new qq.maps.LatLng(event.latLng.getLat(), event.latLng.getLng())
        );
        let polyline = new qq.maps.Polyline({
          path,
          strokeColor: '#ff0000',
          strokeWeight: 3,
          editable: false,
          map: map,
        });
        this.model.route.push({
          lat: event.latLng.getLat(),
          lng: event.latLng.getLng(),
        });
      });
    }
  },
};
</script>

<style lang="scss" scoped>
.sub-title {
  padding-top: 30px;
  margin-bottom: 20px;
  text-align: center;
  font-size: 20px;
  color: #666;
  border-top: 1px dashed #e1e1e1;
}
// 重绘按钮
.repaint-btn {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 999;
  width: 150px;
}
</style>